package com.party.admin.biz.refund;

import com.party.admin.biz.activity.MemberActBizService;
import com.party.core.exception.BusinessException;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderFormInfo;
import com.party.core.model.order.OrderTrade;
import com.party.core.model.order.PaymentWay;
import com.party.core.model.wechat.WechatMerchants;
import com.party.core.service.order.IOrderFormInfoService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderTradeService;
import com.party.core.service.wechat.IWechatMerchantsService;
import com.party.pay.model.refund.AliPayRefundInput;
import com.party.pay.model.refund.WechatPayRefundInput;
import com.party.pay.model.refund.WechatPayRefundResponse;
import com.party.pay.service.refund.RefundAliBizService;
import com.party.pay.service.refund.RefundOrderBizService;
import com.party.pay.service.refund.RefundWechatBizService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.function.Function;

/**
 * 退款业务
 * Created by wei.li
 *
 * @date 2017/3/31 0031
 * @time 19:22
 */
@Service
public class RefundBizService {

	/********************** 支付宝 ***********************/
	// 支付网关
	@Value("#{refund_ali['alipay.gateway']}")
	private String gateway;

	// 接口名称
	@Value("#{refund_ali['alipay.method']}")
	private String method;

	// 应用id
	@Value("#{refund_ali['alipay.appid']}")
	private String appId;

	// 应用私钥
	@Value("#{refund_ali['alipay.privatekey']}")
	private String privateKey;

	// 支付宝公钥
	@Value("#{refund_ali['alipay.publickey']}")
	private String publickey;

	// 签名方式
	@Value("#{refund_ali['alipay.sign_type']}")
	private String signType;
	/********************** 支付宝 ***********************/

	/********************** 微信 ***********************/

	// 微信商户证书
	@Value("#{refund_wechat['wechat.cert.path']}")
	private String certPath;


	// 微信退款接口路径
	@Value("#{refund_wechat['wechat.refundUrl']}")
	private String refundUrl;
	/********************** 微信 ***********************/

	@Autowired
	IOrderTradeService orderTradeService;

	@Autowired
	RefundAliBizService refundAliBizService;

	@Autowired
	RefundWechatBizService refundWechatBizService;

	@Autowired
	RefundOrderBizService refundOrderBizService;

	@Autowired
	MessageOrderBizService messageOrderBizService;
	
	@Autowired
	IOrderFormInfoService orderFormInfoService;

	@Autowired
	IWechatMerchantsService wechatMerchantsService;

	@Autowired
	private MemberActBizService memberActBizService;

	@Autowired
	private IOrderFormService orderFormService;

	protected static Logger logger = LoggerFactory.getLogger(RefundBizService.class);

	/**
	 * 处理退款
	 * 
	 * @param orderId 订单编号
	 * @return 退款结果
	 * @throws Exception 异常信息
	 */
	public Object refund(String orderId, Integer refundFee) throws Exception {
		if (StringUtils.isEmpty(orderId)) {
			logger.error("订单号不能为空");
			return null;
		}
		OrderTrade orderTrade = orderTradeService.findByOrderId(orderId);
		if (orderTrade == null) {
			logger.error("订单支付流水不存在");
			return null;
		}
		if (orderTrade.getType().equals(PaymentWay.ALI_PAY.getCode())) {

			// 支付宝
			AliPayRefundInput input = new AliPayRefundInput();
			input.setAppId(appId);
			input.setGateway(gateway);
			input.setMethod(method);
			input.setPrivateKey(privateKey);
			input.setPublickey(publickey);
			input.setSignType(signType);
			return refundAliBizService.getRefundResponse(input, orderId);
		} else if (orderTrade.getType().equals(PaymentWay.WECHAT_PAY.getCode())) {
			OrderForm orderForm = orderFormService.get(orderId);
			if (null == orderForm) {
				throw new Exception("订单不存在");
			}

			// 微信
			WechatPayRefundInput input = new WechatPayRefundInput();
			OrderFormInfo orderFormInfo = orderFormInfoService.findByOrderId(orderId);
			if (orderFormInfo != null) {
				input.setAppId(orderFormInfo.getAppId());
				input.setMchId(orderFormInfo.getMchId());
				input.setApiKey(orderFormInfo.getApiKey());
			} else {
				WechatMerchants wechatMerchants = wechatMerchantsService.findBymerchantId(orderForm.getMerchantId());
				if (null == wechatMerchants) {
					throw new BusinessException("商户信息不存在");
				}
				input.setApiKey(wechatMerchants.getMerchantApiKey());
			}
			
			input.setRefundUrl(refundUrl);
			input.setCertPath(certPath);
			input.setRefundFee(refundFee);
			WechatPayRefundResponse refundResponse = refundWechatBizService.getRefundResponse(input, orderId);
			if (null != refundResponse && "FAIL".equals(refundResponse.getReturnCode()) && "签名错误".equals(refundResponse.getReturnMsg())) {
				WechatMerchants wechatMerchants = wechatMerchantsService.findBymerchantId(orderForm.getMerchantId());
				if (null == wechatMerchants) {
					logger.error("商户信息不存在，orderId：{}，merchantId：{}", orderForm.getId(), orderForm.getMerchantId());
					return refundResponse;
				} else {
					input.setApiKey(wechatMerchants.getMerchantApiKey());
					return refundWechatBizService.getRefundResponse(input, orderId);
				}
			}
			return refundResponse;
		}
		return null;
	}

	/**
	 * 活动退款退款回调
	 * 
	 * @param orderId 订单信息
	 * @param refundResponse 退款响应
	 * @param paymentWay 支付方式
	 * @return 是否成功（true/false）
	 */
	public boolean activityRefundCallback(String orderId, Object refundResponse, Integer paymentWay,
										  String memberActId, OrderForm orderForm) {
		String paymentWayStr = null;
		if (paymentWay.equals(PaymentWay.WECHAT_PAY.getCode())) {
			paymentWayStr = "微信";
		} else if (paymentWay.equals(PaymentWay.ALI_PAY.getCode())) {
			paymentWayStr = "支付宝";
		}
		try {
			refundOrderBizService.updateRefundBusiness(orderId, refundResponse, paymentWay, new Function() {
				@Override
				public Object apply(Object o) {
//					memberActBizService.activityRefund(memberActId, orderForm.getPayment(), orderForm);
					return null;
				}
			});
		} catch (Exception e) {
			logger.error(paymentWayStr + "处理退款业务出错{}", e);
			return false;
		}
		try {
			messageOrderBizService.activityRefundSend(orderId);
		} catch (Exception e) {
			logger.error(paymentWayStr + "退款消息推送异常{}", e);
			return false;
		}
		return true;
	}

	/**
	 * 活动退款退款回调
	 *
	 * @param orderId 订单信息
	 * @param refundResponse 退款响应
	 * @param paymentWay 支付方式
	 * @return 是否成功（true/false）
	 */
	public boolean activityRefundCallback2(String orderId, Object refundResponse, Integer paymentWay,
										   String memberActId, OrderForm orderForm) throws Exception {
		refundOrderBizService.updateRefundBusiness(orderId, refundResponse, paymentWay, new Function() {
			@Override
			public Object apply(Object o) {
//					memberActBizService.activityRefund(memberActId, orderForm.getPayment(), orderForm);
				return null;
			}
		});
		return true;
	}
}
